import { reqGetGoodsList } from '@/api/goods'

Page({
  // 页面的初始数据
  data: {
    goodsList: [],
    leftList: [],
    rightList: [],
    showEmptyState: false,
    total: 0,
    isFinish: false, //是否全部加载完毕
    isLoadingFinish: false, //当前页是否加载完成（节流）
    // 请求参数
    reqParams: {
      page: 1,
      limit: 10,
      category1Id: '', //从首页导航分类点击进入
      category2Id: '' //从分类导航分类点击进入
    }
  },

  async getGoodsList() {
    // 在请求前后设置节流阀状态
    this.setData({ isLoadingFinish: true })
    const res = await reqGetGoodsList(this.data.reqParams)
    if (res.code === 200) {
      if (res.data.total === 0) {
        this.setData({
          showEmptyState: true,
          goodsList: []
        })
        return
      }
      // 上拉触底后合并其他页数据
      let merList = [...this.data.goodsList, ...res.data.records]
      // 左右列表数据
      let leftList = merList.filter((item, index) => index % 2 === 0)
      let rightList = merList.filter((item, index) => index % 2 !== 0)
      this.setData({
        goodsList: merList,
        total: res.data.total,
        isLoadingFinish: false,
        leftList,
        rightList
      })
    }
  },

  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    // 赋值
    Object.assign(this.data.reqParams, options)
    this.getGoodsList()
  },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    // 重置数据
    this.setData({
      goodsList: [],
      leftList: [],
      rightList: [],
      total: 0,
      isFinish: false,
      reqParams: {
        ...this.data.reqParams,
        page: 1
      }
    })
    // 重新获取数据
    this.getGoodsList()
    wx.stopPullDownRefresh()
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    // 页面加1
    const { goodsList, total, isLoadingFinish, reqParams } = this.data
    // 判断当前页数据是否加载完
    if (total === 0 || isLoadingFinish) return
    if (goodsList.length < total) {
      this.setData({
        reqParams: {
          ...reqParams,
          page: reqParams.page + 1
        }
      })
      this.getGoodsList()
    } else {
      this.setData({
        isFinish: true
      })
    }
  },

  onShareAppMessage: function () {
    return {
      title: '送给心爱的她',
      path: '/pages/index/index',
      imageUrl: '../../../../assets/images/love.jpg'
    }
  },
  onShareTimeline: function () {}
})
